package com.test.io.bio.client;

import com.test.io.utils.ByteArrayUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * describe: 客户端
 *
 * @author lianying
 * @date 2020/01/21
 */
public class BioClient {
    /**
     * 主机地址
     */
    private String host;
    /**
     * 服务端口
     */
    private int serverPort;
    private Socket socket;
    private OutputStream outputStream;

    public BioClient(String host,int serverPort){
        this.host=host;
        this.serverPort=serverPort;
        socket=new Socket();
        try {
            socket.connect(new InetSocketAddress(host,serverPort),5000);
            outputStream=socket.getOutputStream();
        } catch (IOException e) {
            System.out.println("连接失败");
        }
    }
    /**
     * 发送内容
     *
     * @param s
     * @return
     */
    public boolean send(String s){
        try {
            byte[] bytes = s.getBytes("UTF-8");
            byte [] head=ByteArrayUtils.int2ByteArray(bytes.length);
            outputStream.write(head);
            outputStream.write(bytes);
            outputStream.flush();
            System.out.println("发送消息成功："+s);
            return true;
        } catch (IOException e) {
            System.out.println("发送失败");
            return false;
        }
    }

    /**
     * 关闭连接
     */
    public void close(){
        try {
            if(outputStream!=null)
            {
                outputStream.close();
                outputStream=null;
            }

        } catch (IOException e) {
            System.out.println("输出流关闭失败");
        }
        try {
            if(socket!=null)
            {
                socket.close();
                socket=null;
            }
        } catch (IOException e) {
            System.out.println("客户端关闭失败");
        }


    }
}
